package oakclub.model;

import com.jolbox.bonecp.BoneCP;
import oakclub.global.Enums;
import oakclub.global.Container;
import org.jooq.DSLContext;
import org.jooq.SQLDialect;
import org.jooq.conf.Settings;
import org.jooq.impl.DSL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;

public class BaseModel
{
    protected BoneCP connectionPool;
    protected Settings settings;
    private final Logger logger = LoggerFactory.getLogger(BaseModel.class);

    public BaseModel()
    {
        this.connectionPool = (BoneCP) Container.getComponent(Enums.Component.CONNECTION_POOL);
        this.settings = new Settings().withRenderSchema(false);
    }

    protected interface IFetch
    {
        public Object fetch(DSLContext context, Object ... params) throws Exception;
    }

    protected Object fetch(IFetch f, Object ... params) throws Exception
    {
        Connection connection = null;
        try
        {
            connection = this.connectionPool.getConnection();
            DSLContext context = DSL.using(connection, SQLDialect.MYSQL, this.settings);
            return f.fetch(context, params);
        }
        catch(Exception e)
        {
            this.logger.warn("database issue", e);
            throw e;
        }
        finally
        {
            if(connection != null && !connection.isClosed())
            {
                connection.close();
            }
        }
    }

    protected interface IExecute
    {
        public void execute(DSLContext context, Object ... params) throws Exception;
    }

    protected void execute(IExecute f, Object ... params) throws Exception
    {
        Connection connection = null;
        try
        {
            connection = this.connectionPool.getConnection();
            DSLContext context = DSL.using(connection, SQLDialect.MYSQL, this.settings);

            connection.setAutoCommit(false);
            f.execute(context, params);
            connection.commit();
        }
        catch(Exception e)
        {
            if(connection != null && !connection.isClosed())
            {
                connection.rollback();
            }
            this.logger.warn("database issue", e);
            throw e;
        }
        finally
        {
            if(connection != null && !connection.isClosed())
            {
                connection.close();
            }
        }
    }
}
